package grimbo.goodwinfooty;

import grimbo.goodwinfooty.service.model.FootyMatrix;
import grimbo.goodwinfooty.service.model.Game;
import grimbo.goodwinfooty.service.model.Player;
import grimbo.goodwinfooty.service.model.PlayerPayment;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;

import org.apache.commons.lang.StringEscapeUtils;

public class FootyMatrixToJS {
    private FootyMatrix fm;
    private OutputStream out;
    private PrintWriter pw;

    public FootyMatrixToJS(FootyMatrix fm, OutputStream out) {
        this.fm = fm;
        this.out = out;
    }

    public void convert() throws IOException {
        pw = new PrintWriter(new OutputStreamWriter(out));

        pw.println("function getFootyData () {");
        pw.println("var pls = [];");
        for (int i = 0; i < fm.getPlayers().size(); i++) {
            Player p = fm.getPlayer(i);
            convert(p);
        }
        pw.println("var gs = [];");
        pw.println("var ps = null;");
        for (int i = 0; i < fm.getGames().size(); i++) {
            Game g = fm.getGame(i);
            convert(g);
        }
        pw.println("return {players: pls, games: gs}; ");
        pw.println("};");
        pw.flush();
    }

    private void convert(Player p) {
        Object[] args = new Object[] { String.valueOf(p.getId()), StringEscapeUtils.escapeJavaScript(p.getName()),
                String.valueOf(p.getInheritedDebt()), String.valueOf(p.getOtherPayments()) };
        String s = MessageFormat.format("pls[{0}] = [{0}, ''{1}'', {2}, {3}];", args);
        pw.println(s);
    }

    private void convert(Game g) {
        SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
        pw.println("ps = [];");
        Object[] args = new Object[] { String.valueOf(g.getId()), sdf.format(g.getDate()), String.valueOf(g.getPrice()), "ps" };
        String s = MessageFormat.format("g = [{0}, ''{1}'', {2}, {3}];", args);
        pw.println(s);
        pw.println("gs.push(g);");
        for (int i = 0; i < g.getPayments().size(); i++) {
            PlayerPayment pp = g.getPayment(i);
            convert(pp, g);
        }
    }

    private void convert(PlayerPayment pp, Game g) {
        Object[] args = new Object[] { String.valueOf(g.getId()), String.valueOf(pp.getPlayer().getId()),
                String.valueOf(pp.getPayment()), Boolean.valueOf(pp.isCharged()) };
        String s = MessageFormat.format("ps.push([{0}, {1}, {2}, {3}]);", args);
        pw.println(s);
    }
}
